package org.smth.search.fetcher.impl;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.util.concurrent.Callable;

public abstract class RunnableBase {

	protected boolean running;

	protected Thread thread;

	protected Log log = LogFactory.getLog(this.getClass());

	protected abstract Callable<Object> createRunnable();

	protected boolean isDeamon() {
		return true;
	}

	public synchronized void start() {
		if (isRunning()) {
			return;
		}
		final Callable<Object> runnable = createRunnable();
		Runnable run = new Runnable() {
			public void run() {
				try {
					runnable.call();
				} catch (Throwable e) {
					log.warn("运行出现错误: " + e.getMessage());
					log.warn(e);
				} finally {
					thread = null;
				}
			}
		};
		Thread thread = new Thread(run);
		thread.setDaemon(isDeamon());
		this.thread = thread;
		this.running = true;
		thread.start();
	}

	public synchronized void stop() {
		if (!isRunning()) {
			return;
		}
		this.running = false;
	}

	public boolean isRunning() {
		return thread != null && thread.getState() != Thread.State.TERMINATED;
	}

}
